<?php

namespace App\Api\Controllers;

use App\Api\Requests\WithdrawRequest;
use App\Models\UserLog;
use App\Models\Withdraw;
use Illuminate\Http\Request;

class WithdrawsController extends Controller
{

    public function store(Withdraw $withdraw,WithdrawRequest $request){
        if($request->amount<0 ){
            return $this->error('提现金额不能为0');
        }

        if($request->amount>$this->user()->balance){
            return $this->error('余额不足');
        }

        if(config('withdraw_min') > $request->amount){
            return $this->error('最小提现金额为'.config('withdraw_min'));
        }

        $user_coin = $withdraw->where('user_id',$this->user()->id)->where('status',0)->get();
        if(!$user_coin->isEmpty()){
            return $this->error('还有未审核记录');
        }

        $withdraw->fill($request->all());
        $withdraw->user_id = $this->user()->id;
        if($withdraw->save()){
            (new UserLog())->change(-$withdraw->amount,$this->user()->id,'balance',13,'提现');
        }
        return $this->success($withdraw);
    }



    public function index(Withdraw $withdraw){
        return $this->success($withdraw->where('user_id',$this->user()->id)->orderBy('id','desc')->get());
    }
}
